package com.jakewharton.rxbinding4.component;

import static com.jakewharton.rxbinding4.internal.Preconditions.checkNotNull;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.functions.Consumer;
import ohos.agp.components.TabList;

/**
 * Static factory methods for creating {@linkplain Observable observables} and {@linkplain Consumer
 * actions}* for {@link TabList}.
 */
public final class RxTabList {
    /**
     * Create an observable which emits the selected tab in {@code view}.
     * <p>
     * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe
     * to free this reference.
     * <p>
     * <em>Note:</em> If a tab is already selected, it will be emitted immediately on subscribe.
     *
     * @param view view
     * @return the observable
     */
    @NonNull
    public static Observable<TabList.Tab> selections(@NonNull TabList view) {
        checkNotNull(view, "view == null");
        return new TabListSelectionsObservable(view);
    }

    /**
     * Create an observable which emits selection, reselection, and unselection events for the tabs
     * in {@code view}.
     * <p>
     * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe
     * to free this reference.
     * <p>
     * <em>Note:</em> If a tab is already selected, an event will be emitted immediately on subscribe.
     *
     * @param view view
     * @return the observable
     */
    @NonNull
    public static Observable<TabListSelectionEvent> selectionEvents(@NonNull TabList view) {
        checkNotNull(view, "view == null");
        return new TabListSelectionEventObservable(view);
    }

    /**
     * An action which sets the selected tab of {@code view}.
     * <p>
     * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe
     * to free this reference.
     *
     * @param view view
     * @return the consumer
     */
    @NonNull
    public static Consumer<? super Integer> select(@NonNull TabList view) {
        checkNotNull(view, "view == null");
        return new Consumer<Integer>() {
            @Override
            public void accept(Integer index) throws Throwable {
                if (index < 0 || index >= view.getTabCount()) {
                    throw new IllegalArgumentException("No tab for index " + index);
                }
                // noinspection ConstantConditions
                view.getTabAt(index).select();
            }
        };
    }

    private RxTabList() {
        throw new AssertionError("No instances.");
    }
}
